package com.authine.cloudpivot.ext.controller.trainingData;

import cn.hutool.core.lang.Assert;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 培训周知卡 布置
 **/
@RestController
@RequestMapping("/public/trainingCardArrange")
@Slf4j
public class TrainingCardArrangeController extends BaseController {


    @Autowired
    CloudSqlService sqlService;

    /**
     * 培训周知卡 布置  审批流完成后 调用存储过程
     */
    @RequestMapping("finish")
    public void finish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.TrainingCardArrange, bizId);

        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get("trainingCardArrangeDetail");

//        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        //获取审批人

        String approval = getFileBaseInfoWorkFlowApproval(bizObject);

        for (Map<String, Object> map : list) {
            try {
                //调用存储过程
                callProcess(map, approval);
            } catch (Exception e) {
                log.info("培训周知卡布置调用存储过程失败: {},子表id={}", bizId, map.get("id"));
                log.info(e.getMessage(), e);
            }

        }
    }


//    /**
//     *  调用存储过程
//     *  -----员工培训周知卡   布置
//     * exec   SyncTrainPlan
// *        FID       nvarchar(100),	   ----员工培训基础FID
//     *    PlanCompleteDate  nvarchar(50),   ----计划完成时间  字符串格式 YYYY-MM-DD
//     *    PlanDate      nvarchar(50),	   ----布置时间   字符串格式 YYYY-MM-DD
//     *    WorkDesc	   nvarchar(200),  ----工作说明
//     *    RelateFile	   nvarchar(200)	----相关档案
//     */
//    private void callProcess(Map<String,Object> map){
//        log.info("入参map={}",map);
//
//        //调用存储过程
//        Map<String,Object> trainData = (Map<String, Object>) map.get("trainDataFid");
//        String fid = MapUtils.getString(trainData,"id","");
//        Date planComplete = (Date) map.get("planCompleteDate");
//        String planCompleteDate = "";
//        if (planComplete != null) {
//            planCompleteDate= DateFormatUtils.format(planComplete,"yyyy-MM-dd");
//        }
//        Date plan = (Date) map.get("planDate");
//        String planDate = "";
//        if (plan != null) {
//            planDate= DateFormatUtils.format(plan,"yyyy-MM-dd");
//        }
//        String workDesc = MapUtils.getString(map,"workDesc","");
//        String relateFile = MapUtils.getString(map,"relateFile","");
//
//        Assert.isFalse(StringUtils.isEmpty(fid),"{}不能为空","fid");
//        Assert.isFalse(StringUtils.isEmpty(planCompleteDate),"{}不能为空","planCompleteDate");
//        Assert.isFalse(StringUtils.isEmpty(planDate),"{}不能为空","PlanDate");
//        Assert.isFalse(StringUtils.isEmpty(workDesc),"{}不能为空","workDesc");
//        Assert.isFalse(StringUtils.isEmpty(relateFile),"{}不能为空","relateFile");
//        log.info("\n==========存储过程参数{},{},{},{},{}", fid,planCompleteDate,planDate,workDesc,relateFile);
//        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncTrainPlan '%s','%s','%s','%s','%s'",
//                fid,planCompleteDate,planDate,workDesc,relateFile );
//
//        log.info("\n==========准备调用存储过程:{}",execSql);
//
//        sqlService.execute(CloudSqlService.htEas,execSql);
//
//        log.info("\n=============存储过程执行完成");
//
//    }

    /**
     * exec    [dbo].[SyncTrainPlan]
     *
     * @param map
     * @ComCode nvarchar(50),  -----公司代码
     * @FirstDeptCode nvarchar(50),  ----基层组织代码
     * @FirstPosCode nvarchar(50),  ----第一岗代码
     * @EmpCode nvarchar(50),  ----人员代码
     * @TypeCode nvarchar(20),  ----类型代码 PD  CA
     * @FunCode nvarchar(20),  ----职能代码
     * @ArchCode nvarchar(100),  ----档案代码
     * @ArchName nvarchar(100),  ----档案名称
     * @MainDeptCode nvarchar(100),  ----主责部门代码
     * @MainPosCode nvarchar(100),  ----主责岗代码
     * @ManageDeptCode nvarchar(100),  ----管理部门代码
     * @ManagePosCode nvarchar(100),  ----管理岗代码
     * @StudyPosCode nvarchar(100),  ----学习岗代码
     * @StudyReq nvarchar(20),  ----学习要求  1   2   3
     * @AuditDate nvarchar(50),  ----授权审批时间
     * @PlanCompleteDate nvarchar(50), ----计划完成时间
     * @PlanDate nvarchar(50), ----布置时间
     * @WorkDesc nvarchar(200),    ----工作说明
     * @RelateFile nvarchar(200), ----相关档案
     * @Auditor nvarchar(100) ----审批人  02.0100 张三
     */
    private void callProcess(Map<String, Object> map, String approval) {
        log.info("入参map={}", map);

        String comcode = MapUtils.getString(map, "comcode", "");//公司代码
        String baseorgCode = MapUtils.getString(map, "baseorgCode", "");//基层组代码
        String pos1Code = MapUtils.getString(map, "pos1Code", "");//第一岗代码
        String personCode = MapUtils.getString(map, "personCode", "");//人员代码

        String filetypeCode = MapUtils.getString(map, "filetypeCode", "");//类型代码
        String txttype = MapUtils.getString(map, "txttype", "");//类型
        String filetypeCodeValue = StringUtils.isNotBlank(txttype) ? txttype : filetypeCode;

        String txtFunCode = MapUtils.getString(map, "txtFunCode", "");//职能代码
        String txtTrainData = MapUtils.getString(map, "txtTrainData", "");//档案代码
        String fName = MapUtils.getString(map, "fName", "");//档案名称
        String comdeptFNumber = MapUtils.getString(map, "comdeptFNumber", "");//主责部门代码
        String pos2FNumber = MapUtils.getString(map, "pos2FNumber", "");//主责岗代码
        String manadeptFNumber = MapUtils.getString(map, "manadeptFNumber", "");//管理部门代码
        String pos3FNumber = MapUtils.getString(map, "pos3FNumber", "");//管理岗代码  隐藏管理部门责任岗代码
        String txtStudyPosCode = MapUtils.getString(map, "txtStudyPosCode", "");//学习岗代码  隐藏学习岗代码
        String StudyReqList = MapUtils.getString(map, "StudyReqList", "");//学习要求
//        Date checkDateNewTemp = (Date) map.get("checkDateNew");//授权审批时间
//        String checkDateNew = checkDateNewTemp == null ? "" : DateFormatUtils.format(checkDateNewTemp, "yyyy-MM-dd");
        LocalDateTime checkDateNewTemp = (LocalDateTime) map.get("checkDateNew");
        String checkDateNew =  ObjectUtils.isEmpty(checkDateNewTemp) ? "" : checkDateNewTemp.toLocalDate().toString();


//        Date planCompleteDateTemp = (Date) map.get("planCompleteDate");//计划完成时间
//        String planCompleteDate = planCompleteDateTemp == null ? "" : DateFormatUtils.format(planCompleteDateTemp, "yyyy-MM-dd");
        LocalDateTime  planCompleteDateTemp = (LocalDateTime) map.get("planCompleteDate");
        String planCompleteDate =  ObjectUtils.isEmpty(planCompleteDateTemp) ? "" : planCompleteDateTemp.toLocalDate().toString();


//        Date planDateTemp = (Date) map.get("planDate");//布置时间
//        String planDate = planDateTemp == null ? "" : DateFormatUtils.format(planDateTemp, "yyyy-MM-dd");
        LocalDateTime planDateTemp = (LocalDateTime) map.get("planDate");
        String planDate =  ObjectUtils.isEmpty(planDateTemp) ? "" : planDateTemp.toLocalDate().toString();


        String workDesc = MapUtils.getString(map, "workDesc", "");//工作说明
        String relateFile = MapUtils.getString(map, "relateFile", "");//相关档案

        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncTrainPlan '%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                comcode, baseorgCode, pos1Code, personCode, filetypeCodeValue,
                txtFunCode, txtTrainData, fName, comdeptFNumber, pos2FNumber,
                manadeptFNumber, pos3FNumber, txtStudyPosCode, StudyReqList, checkDateNew,
                planCompleteDate, planDate, workDesc, relateFile, approval);

        log.info("\n==========准备调用存储过程:{}", execSql);

        sqlService.execute(CloudSqlService.htEas, execSql);

        log.info("\n=============存储过程执行完成");

    }


    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject) {


        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        final String finalActivityCode = "Activity8";
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }

        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }

        UserModel user = getOrganizationFacade().getUser(participant);


        return new StringBuilder(user.getEmployeeNo()).append(" ").append(user.getName()).toString();
    }


    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map data) {

        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.funOneLevelBase);
        String oneLevelCode = (String) data.get("oneLevelCode");
        String funCode = (String) data.get("funCode");

        StringBuilder sql = new StringBuilder("select id  from ").append(tableName)
                .append(" where funCode='").append(funCode).append("' and oneLevelCode='")
                .append(oneLevelCode).append("';");

        Map<String, Object> map = sqlService.getMap(sql.toString());

        return (String) map.get("id");
    }

    /**
     * 转换成  基础表-总公司档案 的数据
     *
     * @param map
     * @param auditDate
     * @return
     */
    private Map<String, Object> fileInfoBaseMap(Map<String, Object> map, String auditDate, String auditer) {
        Map<String, Object> data = new HashMap<>();

        //审批时间
        data.put("auditDate", map.get("auditDate"));
        //审批人
        data.put("auditer", map.get("auditer"));
        //职能代码隐藏
        data.put("funCode", map.get("funCode"));
        //职能总责部门代码隐藏
        data.put("funDutyDeptCode", map.get("funDutyDeptCode"));
        //职能总责部门
        data.put("funDutyDeptName", map.get("funDutyDeptName"));
        //职能
        data.put("funName", map.get("funName"));
        //一级代码
        data.put("oneLevelCode", map.get("oneLevelCode"));
        //一级职责
        data.put("oneLevelDuty", map.get("oneLevelDuty"));
        //职能代码
        data.put("relevFun", map.get("relevFun"));
        //职能总责部门代码
        data.put("relevFunDutyDept", map.get("relevFunDutyDept"));

        //审批时间
        data.put("auditDate", auditDate);
        //审批人
        data.put("auditer", auditer);

        return data;
    }
}
